﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.BusinessLogic.FileTransferService;
using FileManager_Client.Utility;

namespace FileManager_Client.PresentationLayer
{
    public partial class DownloadTask : Form
    {
        private FileResult fileResult;
        private ToolStripStatusLabel toolStripStatusLabel;
        private UserLoginResult userSession;
        private ServerFiles serverFiles;
        private string currentSavePath;
        private bool doubleClick;
        public DownloadTask(FileResult parentfileResult, ToolStripStatusLabel toolStripStatusLabelParent, ServerFiles parentForm,string savePath,bool isDoubleClick=false)
        {
            InitializeComponent();
            skinEngine1.SkinFile = "office2007.ssk";
            fileResult = parentfileResult;
            toolStripStatusLabel = toolStripStatusLabelParent;
            toolStripStatusLabel.Text = string.Format("1个下载任务;");
            serverFiles = parentForm;
            currentSavePath = savePath;
            doubleClick = isDoubleClick;
            userSession = CacheGlobal.GetCache(GlobalString.System_Config_String.UserSession) as UserLoginResult;
            lb_FileName.Text += parentfileResult.FileNamek__BackingField;
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
    //        try
    //        {
    //            var wcf_FileTransferService =
    //CacheGlobal.GetCache(GlobalString.System_Config_String.Wcf_FileTransferServiceCacheKey) as
    //FileTransfer_ServiceClient;
    //            //var fileSize = (long) fileResult.FileSizek__BackingField.Replace("kb");
    //            //DriveInfo.GetDrives()[].AvailableFreeSpace
    //            if (File.Exists(currentSavePath) && doubleClick)
    //                    File.Delete(currentSavePath);
    //            var downloadCrim = false;
    //            if (File.Exists(currentSavePath))
    //            {
    //                if (XtraMessageBox.Show("文件已存在，是否覆盖下载?", GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
    //                {
    //                    downloadCrim = true;
    //                    File.Delete(currentSavePath);
    //                }
    //            }
    //            else
    //                downloadCrim = true;
    //            if(downloadCrim)
    //            {
    //                Stream inputStream;
    //                var fileId = fileResult.FileSidk__BackingField;
    //                var userId = userSession.UserIdk__BackingField;
    //                var folderId = fileResult.ParentIdk__BackingField;
    //                var length = long.Parse(fileResult.FileSizek__BackingField.Replace("kb", ""));
    //                if (wcf_FileTransferService.State != CommunicationState.Opened)
    //                    wcf_FileTransferService.Open();
    //                var fileLength = wcf_FileTransferService.DownloadFile(fileId,userId, out inputStream);
    //                // write server stream to disk
    //                using (var writeStream = new FileStream(currentSavePath, FileMode.CreateNew, FileAccess.Write))
    //                {
    //                    var chunkSize = 2048;
    //                    var buffer = new byte[chunkSize];
    //                    do
    //                    {
    //                        // read bytes from input stream
    //                        var bytesRead = inputStream.Read(buffer, 0, chunkSize);
    //                        if (bytesRead == 0) break;
    //                        // write bytes to output stream
    //                        writeStream.Write(buffer, 0, bytesRead);
    //                        // report progress from time to time
    //                        pb_Upload.Invoke((EventHandler)delegate
    //                        {
    //                            pb_Upload.Value = (int)(writeStream.Position * 100 / length);
    //                        });
    //                    } while (true);
    //                    writeStream.Close();
    //                }
    //                // close service client
    //                inputStream.Dispose();
    //                if (doubleClick)
    //                    Process.Start(currentSavePath);
    //                else
    //                {
    //                    if(XtraMessageBox.Show("下载成功,是否直接打开文件位置?", GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
    //                        Process.Start("Explorer.exe", "/select," + currentSavePath);
    //                }
    //            }
    //            isClose = true;
    //            Invoke((EventHandler)delegate
    //            {
    //                Close();
    //            });
    //            GC.Collect();
    //        }
    //        catch (Exception ex)
    //        {
    //            LogLoader.Instance.Log.Error("download backgroundWorker_DoWork has problem", ex);
    //            Invoke((EventHandler)delegate
    //            {
    //                toolStripStatusLabel.Text = string.Format("{0}个下载任务;", 0);
    //            });
    //            XtraMessageBox.Show("下载失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
    //            isClose = true;
    //            Invoke((EventHandler)delegate
    //            {
    //                Close();
    //            });
    //            GC.Collect();
    //        }

        }



        private bool isClose;
        private void DownloadTask_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!isClose)
                e.Cancel = true;
            Invoke((EventHandler) delegate
                                      {
                                          toolStripStatusLabel.Text = string.Format("0个下载任务;");
                                      });
        }

        private void DownloadTask_Shown(object sender, EventArgs e)
        {
            try
            {
                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += backgroundWorker_DoWork;
                backgroundWorker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("DownloadTask_Shown has problem", ex);
                XtraMessageBox.Show("下载失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void uploadStreamWithProgress_ProgressChanged(object sender, StreamWithProgress.ProgressChangedEventArgs e)
        {
            if (e.Length != 0)
                pb_Upload.Invoke((EventHandler)delegate
                {
                    pb_Upload.Value = (int)(e.BytesRead * 100 / e.Length);
                });
        }
    }
}
